package com.ityuwen.mengyagushi.album.api;

import com.ityuwen.mengyagushi.album.config.MinioConstantProperties;
import com.ityuwen.mengyagushi.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @PostMapping("fileUpload")
    public Result<Object> fileUpload(MultipartFile file){ // 通过参数接受前端的文件对象，参数名必须是file

        try {
            // 1.初始化MinioClient对象：连接上minIO，链接地址、用户名和密码
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(this.minioConstantProperties.getEndpointUrl())
                    .credentials(this.minioConstantProperties.getAccessKey(), this.minioConstantProperties.getSecretKey())
                    .build();

            // 2.判断bucket是否存在，如果不存在则通过程序创建
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.minioConstantProperties.getBucketName()).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.minioConstantProperties.getBucketName()).build());
            }


            // 3.把图片上传到MinIO服务器
            String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" +
                    StringUtils.replace(UUID.randomUUID().toString(), "-", "") + "." +
                    StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            minioClient.putObject(PutObjectArgs.builder()
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .bucket(this.minioConstantProperties.getBucketName())
                    .object(path)
                    .build());

            // 4.返回图片的回显地址
            String url = this.minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + path;
            // System.out.println(url);
            return Result.ok(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
